package jhunter.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import jhunter.dao.bo.BaseObject;
import jhunter.dao.select.SelectColumn;
import jhunter.dao.type.TypeHandlerFactory;

import org.springframework.jdbc.core.RowMapper;

public class ObjectRowMapper implements RowMapper<BaseObject> {

	private EntityExt entity ;
	
	private List<SelectColumn> columns ;
	
	
	public ObjectRowMapper(EntityExt entity, List<SelectColumn> columns) {
		super();
		this.entity = entity;
		this.columns = columns;
	}


	@Override
	public BaseObject mapRow(ResultSet rs, int rowNum) throws SQLException {
		List<String> refs = entity.getRefRelationships();
		BaseObject bo = entity.getMappingInstanceObject();
		if (refs.size() > 0) {
			for (String refName : refs) {
				EntityExt e = entity.getRefEntity(entity.getRelationshipsMap().get(refName).getTargetId());
				bo.put(refName, e.getMappingInstanceObject());
			}
		}
		for (SelectColumn c : columns) {
			String type = c.getTypeName();
			Object value = TypeHandlerFactory.getTypeHandler(type).getJavaObject(rs, c.getColumnName());
			if (c.getRefName() == null) {
				bo.put(c.getPropertyName(), value);
			} else {
				((BaseObject) bo.get(c.getRefName())).put(c.getPropertyName(), value);
			}
		}
		return bo;
	}

}
